import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as APIService from '../../../axios/api_px'
import * as DingTalkSettingsService from '../../../axios/DingTalkSettings'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareNum, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import { StartOrStopList } from '../../../utils/global';
import SearchForm from './SearchForm';
import AddSelfChecking from './AddSelfChecking';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class SelfCheckingManage extends Component {
    state = {
        procedureData: [],  // 工序list
        modelData: [],  // 机型list
        dataSource: [],
        visible: false,
        advanced: false,
        searchItem: {},
        pageSize: 10,
        pageNum: 1,
        total: 0,
        columns: [
            {
                title: '序号',
                dataIndex: 'dataIndex',
                align: 'center',
                width: 50,
                render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
            },
            {
                title: '表单编码',
                dataIndex: 'formCode',
                width: 100,
                sorter: (a, b) => compareString(a.formCode, b.formCode)
            },

            {
                title: '表单名称',
                width: 180,
                dataIndex: 'formName',
                sorter: (a, b) => compareString(a.formName, b.formName),
            },
            {
                title: '适用机型',
                width: 300,
                // allowEllipsis: true,
                dataIndex: 'model',
                sorter: (a, b) => compareString(a.model, b.model)
            },
            // {
            //     title: '适用岗位',
            //     width: 180,
            //     // allowEllipsis: true,
            //     dataIndex: 'post',
            //     sorter: (a, b) => compareString(a.post, b.post),
            // },
            {
                title: '适用工序',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'procedureName',
                sorter: (a, b) => compareString(a.procedureName, b.procedureName),
            },
            {
                title: '工序编码',
                width: 100,
                // allowEllipsis: true,
                dataIndex: 'procedureCode',
                sorter: (a, b) => compareString(a.procedureCode, b.procedureCode),
            },
            {
                title: '表格编码',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'tableCode',
                sorter: (a, b) => compareString(a.tableCode, b.tableCode),
            },
            {
                title: '创建人',
                width: 100,
                // allowEllipsis: true,
                dataIndex: 'creater',
                sorter: (a, b) => compareString(a.creater, b.creater)
            },
            {
                title: '创建时间',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'createTime',
                sorter: (a, b) => compareDate(a.createTime, b.createTime),
            },
            {
                title: '状态',
                width: 100,
                dataIndex: 'isDelete',
                sorter: (a, b) => compareNum(a.isDelete, b.isDelete),
                render: (text, record, index) => {
                    let a = StartOrStopList.find(item => item.id == text)
                    return <Badge color={a?.color} text={a?.value}></Badge>
                }
            },
            {
                title: '操作',
                width: 200,
                dataIndex: 'opts',
                render: (text, record) => <>
                    <a onClick={() => this.openDetails(record)}>编辑表单</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.changeStates(record)}>{record.isDelete == 0 ? '停用' : '启用'}</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.delete(0, record)}>删除</a>
                </>
            },
            { dataIndex: '' }
        ],
        selectedRows: [],
        selectedRowKeys: [],
        downloadLoading: false,
        drawerVisible: false,  // 新增
    };
    componentDidMount() {
        this.init()
        if (this.props.location.data) {
            this.setState({ searchItem: this.props.location.data.searchItemFather }, this.fetch)
        } else {
            this.fetch()
        }
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    init = () => {
        // 适用机型查询
        APIService.queryProductModel({ "pageNum": 1, "pageSize": 1000 }).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            this.setState({ modelData: res.data.data.data })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
        // 工序查询
        APIService.addReturnMessage().then(res => {
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg)
                return
            }
            this.setState({ procedureData: res.data.data })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true })
        const { searchItem } = this.state
        searchItem.pageNum = pageNum
        searchItem.pageSize = pageSize

        APIService.querySelfCheck(searchItem).then(res => {
            this.setState({ loading: false })
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize, selectedRowKeys: [], selectedRows: [], row: [] })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }

    // 点击新增按钮
    add = () => {
        this.setState({ drawerVisible: true })
    }
    // 保存
    onHandleOk = () => {
        console.log('add');
        this.formDrawer.validateFields(async (err, value) => {
            if (err) return;
            if (value.procedure) {
                value.procedureCode = value.procedure.key
                value.procedureName = value.procedure.label
            }
            this.setState({ loading_submit: true });

            value.createrId = localStorage.getItem('userId')
            value.model = value.model.join(',')

            console.log(value, '新增******************');
            this.addSelfCheck(value)
        })
    }
    // 新增/修改
    addSelfCheck = async (value) => {
        await APIService.addSelfCheck(value).then(res => {
            this.setState({ loading_submit: false })
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            openSuccessModal(res.data.msg);
            this.handleCancel();
        }).catch(err => {
            this.setState({ loading_submit: false });
            openModalMessage('error', err.message);
            return;
        })
    }
    // 点击删除按钮
    delete = (type, record = {}) => {
        let arr = [], data = ''
        if (type == 0) {
            // arr.push(record.id)
            data += 'idList=' + record.id + '&'
        } else if (type == 1) {
            const { selectedRows } = this.state
            if (!selectedRows || !selectedRows.length) {
                openModalMessage('warning', '请选择要删除的数据！');
                return;
            }
            selectedRows.map(item => {
                // arr.push(item.id)
                data += 'idList=' + item.id + '&'
            })
        }

        // let data = {
        //     "idList": arr,
        //     "userId": localStorage.getItem('userId')
        // }
        const that = this;
        Modal.confirm({
            title: '提示',
            content: '确认要删除所选数据吗？',
            onOk: async () => {
                await APIService.deleteSelfCheck(data).then(res => {
                    if (res.data.code !== 200) {
                        openModalMessage('warning', res.data.msg);
                        return;
                    }
                    openSuccessModal(res.data.msg);
                    that.fetch();
                }).catch(err => {
                    openModalMessage('error', err.message);
                    return;
                })
            }
        })
    }
    // 停用/启用
    changeStates = (record) => {
        console.log('停用/启用');
        let value = { ...record }
        const that = this;
        Modal.confirm({
            title: '提示',
            content: `确定是否${value.isDelete == 0 ? '停用' : '启用'}？`,
            onOk: async () => {
                value.isDelete = value.isDelete ? 0 : 1
                await that.addSelfCheck(value)
            }
        })
    }
    handleCancel = e => {
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            visible: false,
            drawerVisible: false,
            selectedRowKeys: [],
            selectedRows: [],
        });
        this.fetch();
    };

    handleSearch = value => {
        if (value.createTime) {
            value.createTime = value.createTime.format('YYYY-MM-DD')
        }
        this.setState({ searchItem: value }, this.fetch);
    };

    onHandleAdvanced = () => {
        this.setState({ advanced: !this.state.advanced })
    }
    loadData = (value, dataSource) => {
        console.log(value, dataSource)
    }
    // 选择某一行数据
    chooseRow = record => {
        let flag = true;
        let index = 0;
        this.state.selectedRowKeys.forEach((row, i) => {
            if (row === record.id) {
                flag = false;
                index = i;
            }
        })
        const selectedRowKeys = this.state.selectedRowKeys;
        const selectedRows = this.state.selectedRows;
        if (flag) {
            selectedRowKeys.push(record.id);
            selectedRows.push(record);
        } else {
            selectedRowKeys.splice(index, 1);
            selectedRows.splice(index, 1);
        }
        this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
    };
    download = () => {
        const { selectedRows } = this.state;
        if (selectedRows.length) {
            this.setState({ downloadLoading: true });
            // APIService.exportProductionOrderParentExcel({ dtoList: selectedRows }).then(res => {
            //     //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            //     let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            //     // 创建A标签
            //     let link = document.createElement('a')
            //     link.style.display = 'none'
            //     link.href = url
            //     // 设置的下载文件文件名
            //     const fileName = decodeURI('生产订单管理（父表）');
            //     // 触发点击方法
            //     link.setAttribute('download', fileName)
            //     document.body.appendChild(link)
            //     link.click()
            //     this.setState({ downloadLoading: false })
            // })
        } else {
            Modal.confirm({
                title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
                onOk: async () => {
                    await this.fetchAll();
                    const { dataSourceAll } = this.state;
                    // await APIService.exportProductionOrderParentExcel({ dtoList: dataSourceAll }).then(res => {
                    //     //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
                    //     let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                    //     // 创建A标签
                    //     let link = document.createElement('a')
                    //     link.style.display = 'none'
                    //     link.href = url
                    //     // 设置的下载文件文件名
                    //     const fileName = decodeURI('生产订单管理（父表）');
                    //     // 触发点击方法
                    //     link.setAttribute('download', fileName)
                    //     document.body.appendChild(link)
                    //     link.click()
                    //     this.setState({ downloadLoading: false })
                    // })
                },
                onCancel() { }
            })
        }
    }
    fetchAll = async () => {
        const { searchItem, total } = this.state
        searchItem.pageNum = 1
        searchItem.pageSize = total
        await APIService.querySelfCheck(searchItem).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            const dataSourceAll = res.data.data.data
            const selectedRowKeys = dataSourceAll.map(item => item.id);
            this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 打开详情页
    openDetails = (record) => {
        const { searchItem } = this.state;
        localStorage.setItem('SelfCheckingManage_searchItem', JSON.stringify(searchItem));
        localStorage.setItem('SelfCheckingManage_detailsList', JSON.stringify(record));
        this.props.history.push({ pathname: "/SelfCheckingManage_Detail", data: { formData: record, searchItemFather: searchItem } })
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({
            searchItem: {}
        }, this.fetch);
    }
    render() {
        const { loading, dataSource, advanced, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem, modelData, procedureData, drawerVisible, loading_submit } = this.state;
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                })
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                const keys = [... this.state.selectedRowKeys];
                const rows = [... this.state.selectedRows];
                if (selected) {
                    changeRows.forEach(row => {
                        if (isInvalidObject(keys.find(key => key === row.id))) {
                            keys.push(row.id);
                            rows.push(row);
                        }
                    })
                } else {
                    changeRows.forEach(row => {
                        keys.splice(keys.indexOf(row.id), 1);
                        rows.splice(rows.indexOf(row), 1);
                    })
                }
                this.setState({ selectedRows: rows, selectedRowKeys: keys })
            }
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <SearchForm onSearch={this.handleSearch}
                        onClick={this.onHandleAdvanced}
                        advanced={advanced}
                        searchItem={searchItem}
                        StartOrStopList={StartOrStopList}
                        procedureData={procedureData}
                        resetForm={this.resetForm}
                        ref={node => (this.formSearch = node)}
                    />
                </BasicLayoutSearch>
                <BasicLayout buttons={[
                    <Button key={1} type="primary" onClick={() => this.add()} icon="plus">新增</Button>,
                    <Button key={2} type="primary" onClick={() => this.delete(1)} icon="delete">删除</Button>,
                    <Button type="primary" key={8} onClick={() => { this.download() }} icon="download" loading={downloadLoading}>导出</Button>,
                ]} name="自检表单维护" icon="table">
                    <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
                    <TableCustomize
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        allowRowEdit
                        allowEditable={this.loadData}
                        rowSelection={rowSelection}
                        onRow={(record, rowKey) => ({
                            onClick: this.chooseRow.bind(this, record, rowKey),
                        })}
                    />
                    <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                </BasicLayout>

                {/* 新增 */}
                <Drawer
                    width={400}
                    visible={drawerVisible}
                    title={'新增'}
                    onClose={this.handleCancel}
                    maskClosable={false}
                    destroyOnClose
                >
                    <AddSelfChecking
                        onOk={this.onHandleOk}
                        ref={node => (this.formDrawer = node)}
                        onClose={this.handleCancel}
                        modelData={modelData}
                        procedureData={procedureData}
                        StartOrStopList={StartOrStopList}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk} loading={loading_submit}>
                            {'确认'}
                        </Button>
                    </div>

                </Drawer>
            </div>
        );
    }
}
export default Form.create()(withRouter(SelfCheckingManage));